
#include "McuRPCManager.h"
#include "log/log.h"

namespace android {

McuRPCManager* McuRPCManager::mSingleton = NULL;

McuRPCManager* McuRPCManager::getInstance() {
    if (mSingleton == NULL) {
        mSingleton = new McuRPCManager();
    }
    return mSingleton;
}

McuRPCManager::McuRPCManager() {
    int queue_size = 15;
    int buffer_size = 1024;

    mSpiBufferQueue = new BufferQueue<McuRPCBuffer>(queue_size, buffer_size);
    mSpiReader = new ReaderThread(this, McuRPCManager::RPC_SPI, mSpiBufferQueue);
    mSpiDispatcher = new DispatcherThread(this, McuRPCManager::RPC_SPI, mSpiBufferQueue);

    mUartBufferQueue = new BufferQueue<McuRPCBuffer>(queue_size, buffer_size);
    mUartReader = new ReaderThread(this, McuRPCManager::RPC_UART, mUartBufferQueue);
    mUartDispatcher = new DispatcherThread(this, McuRPCManager::RPC_UART, mUartBufferQueue);

    mSpiSender = new McuRPCSender(McuRPCManager::RPC_SPI);
    mUartSender = new McuRPCSender(McuRPCManager::RPC_UART);
}

McuRPCManager::~McuRPCManager() {

}

void McuRPCManager::notifyDataReady(int hw_type) {
    if (hw_type == RPC_SPI) {
        if (mSpiDispatcher != NULL) {
            mSpiDispatcher -> onDataReady();
        }
    } else if (hw_type == RPC_UART) {
        if (mUartDispatcher != NULL) {
            mUartDispatcher ->  onDataReady();
        }
    }
}

void McuRPCManager::startSpiInput() {
    mSpiDispatcher -> start();
    mSpiReader -> start();
}

void McuRPCManager::startUartInput() {
    mUartDispatcher -> start();
    mUartReader -> start();
}

void McuRPCManager::registerSpiRPCHandler(McuRPCHandler* handler) {
    ALOGE("registerSpiRPCHandler: %s, handler = %p \n",
            __func__, handler);

    mSpiDispatcher -> registerRPCHandler(handler);
}

void McuRPCManager::registerUartRPCHandler(McuRPCHandler* handler) {
    mUartDispatcher -> registerRPCHandler(handler);
}

int McuRPCManager::sendSpiMessage(int8_t* msg, int len) {
    return mSpiSender -> sendMsg(msg, len);
}

int McuRPCManager::sendUartMessage(int8_t* msg, int len) {
    return mUartSender -> sendMsg(msg, len);
}

} //namespace

